import { useState, useEffect, useRef } from "react";
import { Input, Button, Table, Select, message, Tooltip, Space, Tabs, Modal, Form } from "antd";
import { request } from "../utils/requset";

const { TextArea } = Input;
const { Option } = Select;

export default function SQLQueryPage() {
  const [form] = Form.useForm();
  const [sql, setSql] = useState("");
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState(localStorage.getItem("selectedTab") || "1");
  const [history, setHistory] = useState([]); // 存储 SQL 查询历史
  const [saveSql, setSaveSql] = useState([]); // 存储 SQL 查询历史
  const [SQLResult, setSQLResult] = useState(true); 
  const [visible, setVisible] = useState(false); 
  const [SQLResultError, setSQLResultError] = useState(''); 

  // 获取历史查询记录
  const fetchHistory = async () => {
    try {
      const response = await request.get("/sql/history/get");
      const response2 = await request.get("/sql/sql/get");
      if (response.data && response2.data) {
        setHistory(response.data.history);
        setSaveSql(response2.data.history);
      }
    } catch (error) {
      message.error("获取历史记录失败：" + error.message);
    }
  };

  useEffect(() => {
    fetchHistory();
  }, []);

  // 执行 SQL 查询
  const executeQuery = async () => {
    setActiveTab("1");
    localStorage.setItem("selectedTab", "1");
    const selectedText = sqlRef.current.resizableTextArea.textArea.selectionStart !== sqlRef.current.resizableTextArea.textArea.selectionEnd
      ? sqlRef.current.resizableTextArea.textArea.value.substring(
          sqlRef.current.resizableTextArea.textArea.selectionStart,
          sqlRef.current.resizableTextArea.textArea.selectionEnd
        )
      : sql;

    if (!selectedText.trim()) {
      message.error("请输入SQL语句");
      return;
    }

    setLoading(true);
    try {
      const response = await request.post("/sql/query", {
        sql: selectedText, // 使用选中的文本
        page_size: pageSize,
      });

      if (response.data.error) {
        setSQLResult(false);
        setSQLResultError(response.data.error);
      } else {
        setSQLResult(true);
        setData(response.data.data);

        // 生成列配置
        setColumns(
          response.data.columns.map((col) => ({
            title: col,
            dataIndex: col,
            key: col,
            width: 150,
            ellipsis: true,
            render: (text) => (
              <Tooltip title={text}>
                <div
                  style={{
                    maxWidth: 200,
                    maxHeight: 50,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            ),
          }))
        );

        // 保存 SQL 语句到历史记录
        await saveSQLToHistory(selectedText); // 使用选中的文本
        fetchHistory(); // 刷新历史记录
      }
    } catch (error) {
      message.error("查询失败：" + error.message);
    } finally {
      setLoading(false);
    }
  };
  const SQLSave = async () => {
    const data = form.getFieldsValue();
    if (!data.sqlName.trim()) {
      message.error("请输入SQL名称");
      return;
    }
    if (!data.sql.trim()) {
      message.error("请输入SQL语句");
      return;
    }
    // 保存 SQL 语句到历史记录
    try {
        await request.post("/sql/sql/save", { sql: data.sql, name: data.sqlName });
    } catch (error) {
        message.error("保存SQL失败：" + error.message);
    }
    setVisible(false);
    fetchHistory(); // 刷新历史记录
  };

  // 保存 SQL 查询到 DuckDB
  const saveSQLToHistory = async (sqlText) => {
    try {
      await request.post("/sql/history/save", { sql: sqlText });
    } catch (error) {
      message.error("保存SQL失败：" + error.message);
    }
  };

  // 重新执行历史 SQL 查询
  const rerunQuery = (sqlText) => {
    setSql(sqlText);
  };

  // Tab 切换时存储状态
  const handleTabChange = (key) => {
    setActiveTab(key);
    localStorage.setItem("selectedTab", key);
  };
  const historyColumns = [
    {
      title: '语句',
      dataIndex: 'query',
      key: 'query',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div
            style={{
              maxWidth: 200,
              maxHeight: 50,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              cursor: "pointer", // 添加鼠标指针样式
            }}
            onClick={() => rerunQuery(text)} // 添加点击事件
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '时间',
      dataIndex: 'create_at',
      key: 'create_at',
    },
  ]
  const saveColumns = [
    {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    },
    {
      title: '语句',
      dataIndex: 'query',
      key: 'query',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div
            style={{
              maxWidth: 200,
              maxHeight: 50,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              cursor: "pointer", // 添加鼠标指针样式
            }}
            onClick={() => rerunQuery(text)} // 添加点击事件
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '时间',
      dataIndex: 'create_at',
      key: 'create_at',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Button type="link" onClick={() => {
          Modal.confirm({
            title: '确认删除',
            content: '确定要删除这条记录吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              request.delete('/sql/sql/delete?id='+record.id);
              fetchHistory();
            },
            onCancel() {
              console.log('取消删除');
            },
          });
        }}>删除</Button>
      ),
    },
  ]

  const tabItems = [
    {
      key: "1",
      label: "查询结果",
      children: (
        SQLResult ? (
            <Table
              dataSource={data.map((row, index) => ({ key: index, ...row }))}
              columns={columns}
              pagination={false}
              scroll={{ x: "max-content", y: 450 }}
            />
        ): (<div style={{ color: "red" }}>{SQLResultError}</div>)
      ),
    },
    {
      key: "2",
      label: "保存的SQL",
      children: (
            <Table
                dataSource={saveSql}
                columns={saveColumns}
                scroll={{ y: 450 }}
                pagination={false} // 如果不需要分页，可以禁用分页
            />
      )
    },
    {
      key: "3",
      label: "历史查询",
      children: (
            <Table
                dataSource={history.map((row, index) => ({ key: index, ...row }))}
                columns={historyColumns}
                scroll={{ y: 450 }}
                pagination={false} // 如果不需要分页，可以禁用分页
            />
      )
    },
  ];

  const sqlRef = useRef(null); // 添加 ref 引用
  function openSave() {
    form.setFieldsValue({ sqlName: "", sql: sql });
    setVisible(true);
  }

  return (
    <div>
      <Space style={{ height: "48px" }}>
        行数：
        <Select style={{ width: 200 }} value={pageSize} onChange={(value) => setPageSize(value)}>
          <Option value={10}>10</Option>
          <Option value={20}>20</Option>
          <Option value={50}>50</Option>
          <Option value={100}>100</Option>
        </Select>
        <Button onClick={openSave} loading={loading}>
          保存SQL
        </Button>
        <Button type="primary" onClick={executeQuery} loading={loading}>
          执行查询
        </Button>
      </Space>

      {/* SQL 输入框 */}
      <TextArea
        rows={4}
        placeholder="输入SQL查询语句..."
        value={sql}
        style={{ minHeight: 200 }}
        onChange={(e) => setSql(e.target.value)}
        ref={sqlRef} // 绑定 ref
      />

      <Tabs items={tabItems} activeKey={activeTab} onChange={handleTabChange} />

      <Modal
          title="保存SQL"
          open={visible}
          onCancel={() => setVisible(false)}
          onOk={SQLSave}
          // width={"50vw"}
      >
        <Form
            form={form}
            layout="vertical"
        >
          <Form.Item
              label="SQL名称"
              name="sqlName"
              rules={[{required: true, message: '请输入SQL名称!'}]}
          >
            <Input placeholder="输入SQL名称..." />
          </Form.Item>
          <Form.Item
              label="SQL语句"
              name="sql"
              rules={[{required: true, message: '请输入SQL语句!'}]}
          >
            <TextArea
              rows={4}
              placeholder="输入SQL查询语句..."
              style={{ minHeight: 200, fontFamily: "monospace" }}
            />
          </Form.Item>
        
        </Form>
      </Modal>
    </div>
  );
}
